<template>
  <!-- 滚动区域开始 -->
  <view class="container">
  <z-paging
    ref="paging"
    @scroll="handleScroll"
    :scroll-with-animation="true"
  >
    <template #top>
      <!-- 自定义导航组件 -->
      <CustomNavbar />
    </template>

    <!-- 骨架屏区域开始 -->
    <uv-skeletons :loading="isSkeleton" :skeleton="skeletons" v-for="(index) in 12" :key="index"></uv-skeletons>
    <!-- 骨架屏区域结束 -->
    <block v-if="!isSkeleton">
      <!-- 列表区域开始 -->
      <uni-swipe-action>
          <uni-swipe-action-item
            v-for="(item, index) in commonStore.chatTargetList" :key="index"
          >
            <view class="swipe-action-item">
              <uni-list-chat
                :title="item.target_info.name"
                :avatar-list="handleAvatar(item.target_info.avatar_url)"
                :note="(item.mode == 2 && item.message.from_user ? item.message.from_user?.username + '：' : '') + (item.message?.contents || '')"
                badge-positon="left"
                :badge-text="item.unread_num"
                :to="(item.mode == 1 ? '/pages/chat/index?id=' + item.target_info.friend_id : '/pages/chat/index?gid=' + item.target_info.target_id) + '&mode='+ item.mode"
              >
                <view class="chat-custom-right">
                  <view class="chat-custom-icon">
                    <!-- 免打扰区域 -->
                    <i class="iconfont icon-guanbixiaoxi" v-if="item.target_info.is_disturb == 1"></i>
                  
                    <!-- 置顶区域 -->
                    <i class="iconfont icon-zhiding" v-if="item.target_info.is_top == 1"></i>
                  </view>
                  <text class="chat-custom-text">{{simplifyDateFormat(item.message.create_time)}}</text>
                </view>
              </uni-list-chat>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="swipe-right">
                  <button @click="handleClose(item.id)" class="button delete-button">关闭</button>
              </view>
            </template>
          </uni-swipe-action-item>

          <!-- 服务通知区域开始 -->
          <view @click="goto('/pagesFriend/notify/index')">
            <TridentCellItem
              :item="{
                icon: 'icon-tongzhi',
                icon_bg_color: global.THEME_COLOR,
                title: '服务通知',
                value: simplifyDateFormat(commonStore.newestNotify ? commonStore.newestNotify.create_time : ''),
                desc: commonStore.newestNotify ? commonStore.newestNotify.title : '',
                badge_text: commonStore.unreadNotifyTotal
              }"
              :is_arrows="false"
            />
          </view>
          <!-- 服务通知区域结束 -->
        </uni-swipe-action>
    </block>
  </z-paging>
  </view>
  <!-- 滚动区域结束 -->

  <!-- 返回顶部 -->
  <TridentBackTop @backTop="backTop" :isShowBackTop="isShowBackTop"/>
</template>

<script setup lang="ts">
import { ref, inject, reactive } from 'vue'
import { onShow } from "@dcloudio/uni-app"
import { simplifyDateFormat } from '@/utils/tools'
import { goto } from '@/utils/tools'

// 导入接口
import { reqChatTargetListAPI, reqDeleteChatTargetAPI } from '@/apis/chatTarget'
import { reqNotifyListAPI, reqNotifyTotalAPI } from '@/apis/notify'

// 导入数据类型
import type { ChatTarget, ChatTargetListParams } from '@/types/chatTarget'

// 导入自定义组件
import CustomNavbar from './componets/CustomNavbar.vue'
import { useUserStore } from '@/stores'
import { useCommonStore } from '@/stores'



// --------------- 定义全局变量开始 ---------------
const paging = ref()

// 全局属性
const global: any = inject('global')

// 用户存储
const userStore = useUserStore()

// 公共存储
const commonStore = useCommonStore()
// --------------- 定义全局变量结束 ---------------



onShow(async () => {
  isSkeleton.value = true
  await Promise.all([
    getChatTargetList(),
    getNotifyList(),
    getUnreadNotifyTotal()
  ])

  paging.value.scrollToTop()

  isSkeleton.value = false
})



// --------------- 返回顶部功能开始 ---------------
// 定义是否显示返回顶部
const isShowBackTop = ref(false)

// 返回顶部
const backTop = () => {
  paging.value.scrollToTop()
}

// 当滚动触发时，调用事件用于显示、隐藏返回顶部图标
const handleScroll = (e:any) => {
  isShowBackTop.value = e.detail.scrollTop > 300 ? true : false
}
// --------------- 返回顶部功能结束 ---------------



// --------------- 处理聊天好友开始 ---------------
const params = ref<ChatTargetListParams>({
  uid: 0
})

// 请求聊天对象列表
const getChatTargetList = async () => {
  params.value.uid = userStore.profile.user?.uid
  const result = await reqChatTargetListAPI(params.value)
  // 置顶聊天对象
  let topList: ChatTarget[]  = []

  // 非置顶聊天对象
  let untopList: ChatTarget[] = []
  result.data.chat_targets.forEach((item: ChatTarget) => {
    if (item.message.id) {
      switch (item.message.type) {
        case 2:
          item.message.contents = '[图片]'
          break;
        case 3:
          item.message.contents = '[语音]'
          break;
        case 4:
          item.message.contents = '[视频]'
          break;
        case 5:
          item.message.contents = '[位置]'
          break;
      
        default:
          break;
      }
    }
    if (item.target_info.is_top == 1) {
      topList.push(item)
    } else {
      untopList.push(item)
    }
  })

  commonStore.setChatTargetList([...topList, ...untopList])
}
// --------------- 处理聊天好友结束 ---------------



// ------------- 处理关闭好友聊天开始 -------------
const handleClose = (id: number) => {
  uni.showModal({
    content: '确定要关闭好友聊天吗?',
    confirmColor: global.THEME_COLOR,
    success: async (res) => {
      if (res.confirm) {
        await reqDeleteChatTargetAPI(id +'')
        const index = commonStore.chatTargetList.findIndex((item: ChatTarget) => item.id == id)
        commonStore.chatTargetList.splice(index, 1)

        uni.showToast({
          title: '关闭好友聊天',
          duration: 1000
        })
      }
    }
	})
}
// ------------- 处理关闭好友聊天结束 -------------



// --------------- 处理服务通知开始 ---------------
// 获取通知列表
const getNotifyList = async () => {
  const result = await reqNotifyListAPI({
    uid: userStore.profile.user?.uid,
    private_public: 1,
    page: 1,
    page_size: 1
  })

  // 设置最新通知
  if (result.data.notifies.length > 0) {
    commonStore.setNewestNotify(result.data.notifies[0])
  }
}

// 获取未读通知数量
const getUnreadNotifyTotal = async () => {
  const result = await reqNotifyTotalAPI({
    uid: userStore.profile.user?.uid,
    private_public: 1,
    is_read: '1',
  })

  // unreadNotifyTotal.value = result.data.total
  commonStore.setUnreadNotifyTotal(result.data.total)
}
// --------------- 处理服务通知结束 ---------------



// ----------------- 处理头像开始 -----------------
const handleAvatar = (avatar: string) => {
  const avatarList = []
  if (avatar != '') {
    const list = avatar.split(',')
    list.forEach((item: string) => {
      avatarList.push({url: global.FILE_DOMAIN + item})
    })
  } else {
    avatarList.push({url: '/static/images/default_avatar.png'})
  }

  return avatarList
}
// ----------------- 处理头像结束 -----------------



// --------------- 定义骨架变量开始 ---------------
// 定义是否显示骨架
const isSkeleton = ref(false)

// 定义骨架参数
const skeletons = reactive([{
  type: 'flex',
  num: 1,
  style: 'padding: 15rpx 30rpx 15rpx 25rpx;background-color: #fff;border-bottom: 2rpx solid #f6f6f6;justify-content: space-between;',
  children: [
    // 图片区域
    {
      type: 'custom',
      num: 1,
      style: 'width: 85rpx;height: 85rpx;border-radius: 10rpx;margin-right: -60rpx;'
    },

    {
      type: 'custom',
      num: 2,
      style: ['width: 120rpx;height: 40rpx;', 'width: 400rpx;height: 30rpx;']
    },

    {
      type: 'custom',
      num: 2,
      style: ['width: 80rpx;height: 34rpx;margin-left: 40rpx;', 'width: 120rpx;height: 34rpx;']
    },
  ]
}])
// --------------- 定义骨架变量结束 ---------------
</script>

<style scoped lang="scss">
.container {
  /* #ifdef MP-ALIPAY */
  .swipe-action-item {
    width: 100%;
  }
  /* #endif */
  .chat-custom-right {
    display: flex;
    flex-direction: column;
    .chat-custom-icon {
      display: flex;
      justify-content: flex-end;
      color: #b3b2b2;
      padding-bottom: 10rpx;
      .iconfont {
        font-size: 32rpx;
      }
    }
    .chat-custom-text {
      font-size: 24rpx;
      color: #c7c7c7;
    }
  }
  .swipe-right {
    display: flex;
    height: 94%;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: #df1212;
    }
  }
}
</style>
